﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;

namespace mSpy.UI.Model
{
    public class Stage
    {
        public string DisplayName { get; set; }
        public int Value { get; set; }

        public static List<Stage> GetAll()
        {
            List<Stage> stages = new List<Stage>();

            stages.Add(new Stage { DisplayName = "Pre", Value = (int)MessageProcessingStage.BeforeMainOperationOutsideTransaction });
            stages.Add(new Stage { DisplayName = "Post", Value = (int)MessageProcessingStage.AfterMainOperationOutsideTransaction });

            return stages;
        }
    }

    public class Mode
    {
        public string DisplayName { get; set; }
        public int Value { get; set; }

        public static List<Mode> GetAll()
        {
            List<Mode> modes = new List<Mode>();

            modes.Add(new Mode { DisplayName = "Synchronous", Value = (int)MessageProcessingMode.Synchronous });
            modes.Add(new Mode { DisplayName = "Asynchronous", Value = (int)MessageProcessingMode.Asynchronous });

            return modes;
        }
    }

    public class Pipeline
    {
        public string DisplayName { get; set; }
        public int Value { get; set; }

        public static List<Pipeline> GetAll()
        {
            List<Pipeline> pipelines = new List<Pipeline>();

            pipelines.Add(new Pipeline { DisplayName = "Parent", Value = (int)MessageInvocationSource.Parent });
            pipelines.Add(new Pipeline { DisplayName = "Child", Value = (int)MessageInvocationSource.Child });

            return pipelines;
        }
    }

    public class Message
    {
        public string DisplayName { get; set; }

        public static List<Message> GetAll(CrmService sdk)
        {
            QueryExpression qe = new QueryExpression("sdkmessage");
            qe.ColumnSet = new AllColumns();

            var results = sdk.Execute(new RetrieveMultipleRequest
            {
                Query = qe,
                ReturnDynamicEntities = true
            }) as RetrieveMultipleResponse;

            if (results != null && results.BusinessEntityCollection.BusinessEntities.Count > 0)
            {
                return results.BusinessEntityCollection.BusinessEntities.Cast<DynamicEntity>().Select(a =>
                    new Message
                    {
                        DisplayName = a["name"].ToString()
                    }).OrderBy(a => a.DisplayName).ToList();
            }

            return new List<Message>();
        }
    }
}
